package com.lyloou.practicerabbitmq.listener;

import cn.hutool.json.JSONUtil;
import com.lyloou.practicerabbitmq.entity.Const;
import com.lyloou.practicerabbitmq.entity.Order;
import com.lyloou.practicerabbitmq.entity.OrderStatus;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * @author lilou
 * @since 2021/2/18
 */
@Component
@Slf4j
public class OrderCreatedListener {
    @Autowired
    @Qualifier("orderDb")
    Map<String, Order> orderDb;

    @RabbitListener(queues = Const.q.order, ackMode = "MANUAL")
    public void onMessage(Order order, Channel channel, Message message) throws IOException {
        log.info("写入数据库");
        orderDb.put(order.getOrderId(), order);

        Optional.ofNullable(orderDb.get(order.getOrderId())).ifPresent(data -> {
            // 订单支付
            data.setStatus(OrderStatus.TO_BE_PAYED);
            // 打印订单信息
            log.info("订单创建成功：\n" + JSONUtil.toJsonPrettyStr(data));
        });


        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
